//
//  MoneyViewController.m
//  忘不了
//
//  Created by rimi on 16/7/9.
//  Copyright © 2016年 handuan. All rights reserved.
//

#import "MoneyViewController.h"
#import "SDAutoLayout.h"
#import "MoneyTableViewCell.h"
#import "addMoneyViewController.h"
#import "moneyDetailViewController.h"
#import "BaseRequest+MoneyAndRemember.h"
#import "historyMoneyViewController.h"
#import "UserModel.h"
#import "MJRefresh.h"
#import "CheckWeb.h"
@interface MoneyViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong)UITableView *moneyTableView;
@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic,strong)UIButton *addButton;
@property (nonatomic,strong)UILabel *totalMoneyLabel;
@property (nonatomic,assign)NSInteger total;
@property (nonatomic,strong)UIButton *clearButton;
@property (nonatomic,strong)UIButton *mainButton;
@property (nonatomic,assign)BOOL isSelected;
@end

@implementation MoneyViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    BOOL isWeb = [CheckWeb checkWang];
    if (isWeb == NO) {
        UIAlertController *tip3 = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"修改邮箱成功" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:tip3 animated:YES completion:nil];
        [self performSelector:@selector(disMiss) withObject:nil afterDelay:0.1];
    }else{
    [self loadData];
    }
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    //下拉刷新的三方库
        self.moneyTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
        [self.moneyTableView.mj_header beginRefreshing];
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
                                                         forBarMetrics:UIBarMetricsDefault];//隐藏导航栏返回按钮自带的文字
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"按月查看" style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonTaped)];
    self.title = @"开支";
    
    _dataSource = [NSMutableArray array];
    
    [self initInterface];
    
    //接收通知
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(addMoneyNotification:) name:@"addMoney" object:nil];
}
- (void)disMiss
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)loadData{
    [BaseRequest startGetDataSourceWithForm:@"Money" completionhanlder:^(Response *response) {
        if (response.isSuccess) {
            _dataSource = response.resultObject;
            [_moneyTableView reloadData];
        }
        //加载开支总和
        _total = 0;
        for (int i=0; i<_dataSource.count; i++) {
            _total += [_dataSource[i][@"money"] integerValue];
        }
        if (_total == 0) {
            self.totalMoneyLabel.hidden = YES;
        } else {
            self.totalMoneyLabel.hidden = NO;
            self.totalMoneyLabel.text = [NSString stringWithFormat:@"开支总额:¥%ld",_total];
        }
    }];
}

//- (void)viewDidLoad {
//    [super viewDidLoad];
//    self.view.backgroundColor = [UIColor whiteColor];
//    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
//                                                         forBarMetrics:UIBarMetricsDefault];//隐藏导航栏返回按钮自带的文字
//    
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"按月查看" style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonTaped)];
//    self.title = @"开支";
//    
//    _dataSource = [NSMutableArray array];
//    
//    [self initInterface];
//    
//}

- (void)initInterface {
    _moneyTableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _moneyTableView.dataSource = self;
    _moneyTableView.delegate = self;
    _moneyTableView.rowHeight = 50;
    _moneyTableView.backgroundView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"s.jpg"]];
    [self.view addSubview:_moneyTableView];
    
    _addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_addButton setTitle:@"添加" forState:UIControlStateNormal];
    [_addButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _addButton.backgroundColor = [UIColor colorWithRed:0.902 green:0.3451 blue:0.3686 alpha:1.0];
    _addButton.layer.cornerRadius = self.view.frame.size.width*0.15/2;
    _addButton.layer.shadowOpacity = 0.5;
    _addButton.layer.shadowOffset = CGSizeMake(3, 3);
    [_addButton addTarget:self action:@selector(addButtonTaped) forControlEvents:UIControlEventTouchUpInside];
    _addButton.alpha = 0.1;
    [self.view addSubview:_addButton];
    _addButton.sd_layout
    .rightSpaceToView (self.view,20)
    .bottomSpaceToView(self.view,20)
    .widthIs(self.view.frame.size.width*0.15)
    .heightEqualToWidth();
    
    _clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_clearButton setTitle:@"清空" forState:UIControlStateNormal];
    [_clearButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _clearButton.backgroundColor = [UIColor colorWithRed:0.902 green:0.3451 blue:0.3686 alpha:1.0];
    _clearButton.layer.cornerRadius = self.view.frame.size.width*0.15/2;
    _clearButton.layer.shadowOpacity = 0.5;
    _clearButton.layer.shadowOffset = CGSizeMake(3, 3);
    [_clearButton addTarget:self action:@selector(clearButtonTaped) forControlEvents:UIControlEventTouchUpInside];
    _clearButton.alpha = 0.1;
    [self.view addSubview:_clearButton];
    _clearButton.sd_layout
    .rightSpaceToView (self.view,20)
    .bottomSpaceToView(self.view,20)
    .widthIs(self.view.frame.size.width*0.15)
    .heightEqualToWidth();
    
    _mainButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_mainButton setTitle:@"＋" forState:UIControlStateNormal];
    [_mainButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _mainButton.backgroundColor = [UIColor colorWithRed:0.902 green:0.3451 blue:0.3686 alpha:1.0];
    _mainButton.layer.cornerRadius = self.view.frame.size.width*0.15/2;
    _mainButton.layer.shadowOpacity = 0.5;
    _mainButton.layer.shadowOffset = CGSizeMake(3, 3);
    [_mainButton addTarget:self action:@selector(mainButtonTaped) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_mainButton];
    _mainButton.sd_layout
    .rightSpaceToView (self.view,20)
    .bottomSpaceToView(self.view,20)
    .widthIs(self.view.frame.size.width*0.15)
    .heightEqualToWidth();
    
    _totalMoneyLabel = [[UILabel alloc]init];
    _totalMoneyLabel.textAlignment = NSTextAlignmentLeft;
    _totalMoneyLabel.textColor = [UIColor colorWithRed:0.851 green:0.2745 blue:0.1765 alpha:1.0];
    _totalMoneyLabel.backgroundColor = [UIColor clearColor];
    _totalMoneyLabel.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:_totalMoneyLabel];
    _totalMoneyLabel.sd_layout
    .leftSpaceToView(self.view,20)
    .rightSpaceToView(self.addButton,10)
    .bottomSpaceToView(self.view,0)
    .heightIs(self.view.frame.size.width*0.15);
}

- (void)rightButtonTaped {
    historyMoneyViewController *historyVC = [[historyMoneyViewController alloc]init];
    historyVC.dataArray = self.dataSource;
    NSLog(@"历史开支数据%@",historyVC.dataArray);
    [self.navigationController pushViewController:historyVC animated:YES];
}

- (void)mainButtonTaped {
    self.isSelected = ! _isSelected;
    if (_isSelected) {
        //弹簧动画
        [UIView animateWithDuration:0.3
                              delay:0
             usingSpringWithDamping:0.5
              initialSpringVelocity:0.1
                            options:0
                         animations:^{
                             _addButton.alpha = 1;
                             _clearButton.alpha = 1;
                             _addButton.center = CGPointMake(self.view.frame.size.width-20-self.view.frame.size.width*0.15/2,self.view.frame.size.height*0.8);
                             _clearButton.center = CGPointMake(self.view.frame.size.width-self.view.frame.size.height*0.2,self.view.frame.size.height-20-self.view.frame.size.width*0.15/2);
                         }
                         completion:^(BOOL finished){
                            
                         }];
        
    } else {
        [UIView animateWithDuration:0.3 animations:^{
            _addButton.alpha = 0.1;
            _clearButton.alpha = 0.1;
            _addButton.center = CGPointMake(self.view.frame.size.width-20-self.view.frame.size.width*0.15/2,self.view.frame.size.height-20-self.view.frame.size.width*0.15/2);
            _clearButton.center = CGPointMake(self.view.frame.size.width-20-self.view.frame.size.width*0.15/2,self.view.frame.size.height-20-self.view.frame.size.width*0.15/2);
        }];
    }
}

- (void)addButtonTaped {
    addMoneyViewController *addVC = [[addMoneyViewController alloc]init];
    [self.navigationController pushViewController:addVC animated:YES];
}

- (void)clearButtonTaped {
    [BaseRequest removeDataWithUserName:[UserModel shareUserModel].userNmae formName:@"Money"];
    
    [_dataSource removeAllObjects];
    [_moneyTableView reloadData];
    
    _totalMoneyLabel.hidden = YES;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifer = @"viewContrroller";
    MoneyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifer];
    if (!cell){
        cell = [[MoneyTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifer];
    }
    cell.money = [self.dataSource[indexPath.row][@"money"] integerValue];
    [cell loadUIwithData:self.dataSource[indexPath.row]];
    return cell;
}

//选中
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    moneyDetailViewController *moneyDetailVC = [[moneyDetailViewController alloc]init];
    moneyDetailVC.dataDic = self.dataSource[indexPath.row];
    [self.navigationController pushViewController:moneyDetailVC animated:YES];
}

//配置删除按钮的 title
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

//提交编辑状态
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete){
        //1.删除数据
        [_dataSource removeObjectAtIndex:indexPath.row];
        //2.删除表格行视图
        [_moneyTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        //改变总金额
        _total = 0;
        for (int i=0; i<self.dataSource.count; i++) {
            _total += [self.dataSource[i][@"money"] integerValue];
        }
        if (_total == 0) {
            self.totalMoneyLabel.hidden = YES;
        } else {
            self.totalMoneyLabel.hidden = NO;
            self.totalMoneyLabel.text = [NSString stringWithFormat:@"开支总额:¥%ld",_total];
        }
        [BaseRequest deleteDataWithFormName:@"Money" index:indexPath.row completionhanlder:^(Response *response) {
            if (response.isSuccess) {
                [BaseRequest startGetDataSourceWithForm:@"Money" completionhanlder:^(Response *response) {
                    if (response.isSuccess) {
                        self.dataSource = response.resultObject;
                        [self.moneyTableView reloadData];
                    }
                }];
            }
        }];
    }
}

//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
//{
//    return 50;
//}
////自定义表尾
//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
//    
//    UIView *aFooter = [[UIView alloc]init];
//    aFooter.backgroundColor = [UIColor clearColor];
//    
//    _clearButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    _clearButton.backgroundColor = [UIColor colorWithRed:0.851 green:0.8196 blue:0.7686 alpha:1.0];
//    [_clearButton setTitle:@"清空所有数据" forState:UIControlStateNormal];
//    [_clearButton setTitleColor:[UIColor colorWithRed:0.1216 green:0.1216 blue:0.1765 alpha:1.0] forState:UIControlStateNormal];
//    _clearButton.layer.cornerRadius = 10;
//    _clearButton.layer.masksToBounds = YES;
//    _clearButton.tag = 900;
//    [_clearButton setTranslatesAutoresizingMaskIntoConstraints:NO];
//    [_clearButton addTarget:self action:@selector(clearButtonTaped) forControlEvents:UIControlEventTouchUpInside];
//    [aFooter addSubview:_clearButton];
//    
//    _clearButton.sd_layout
//    .centerXIs(self.view.frame.size.width/2)
//    .widthIs(self.view.frame.size.width*0.5)
//    .topSpaceToView(aFooter,10)
//    .bottomSpaceToView(aFooter,10);
//    
//    aFooter.sd_layout
//    .widthIs(self.moneyTableView.frame.size.width)
//    .heightIs(self.view.frame.size.width*0.1)
//    .centerXIs(self.view.frame.size.width/2)
//    .topSpaceToView(self.view,_dataSource.count*50-64);
//    return aFooter;
//}



@end
